import { ref, inject } from 'vue'
import RouterView from './RouterView.vue'
import RouterLink from './RouterLink.vue'

const ROUTER_KEY = '__router__'

class Router {
    public history
    public routes
    public current
    constructor(options) {
        this.history = options.history
        this.routes = options.routes
        this.current = ref(this.history.url)
        this.history.bindEvent(() => {
            console.log('hashchange===')
            this.current.value = window.location.hash.slice(1)
        })
    }
    install(app) {
        app.provide(ROUTER_KEY, this)
        app.component('router-view', RouterView)
        app.component('router-link', RouterLink)
    }
}

const createWebHashHistory = () => {
    const bindEvent = (fn) => {
        window.addEventListener('hashchange', fn)
    }
    return {
        bindEvent,
        url: window.location.hash.slice(1)
    }
}
const createRouter = (options) => {
    return new Router(options)
}
const useRouter = (): Router => {
    return inject(ROUTER_KEY)
}

export {
    createWebHashHistory,
    createRouter,
    useRouter
}
